package com.derbysoft.lowcostadapter.schedule.service;

import com.derbysoft.lowcostadapter.commons.model.Role;
import com.derbysoft.lowcostadapter.commons.model.User;
import com.derbysoft.lowcostadapter.commons.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;

    public UserDetails loadUserByUsername(String name) {
        User user = userRepository.findByName(name);
        if (user == null) {
            user = new User();
            user.setName(name);
            user.setRoles(new ArrayList<Role>());
        }
        return makeUserDetails(user);
    }

    private UserDetails makeUserDetails(final User user) {
        return new UserDetails() {

            public Collection<GrantedAuthority> getAuthorities() {
                ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
                for (Role role : user.getRoles()) {
                    grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
                }
                return grantedAuthorities;
            }

            public String getPassword() {
                return null;
            }

            public String getUsername() {
                return user.getName();
            }

            public boolean isAccountNonExpired() {
                return true;
            }

            public boolean isAccountNonLocked() {
                return true;
            }

            public boolean isCredentialsNonExpired() {
                return true;
            }

            public boolean isEnabled() {
                return !user.getDisabled();
            }
        };
    }

    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
}
